import React, { useState } from 'react'
import styles from "./index.css"
import { Upload, Icon, Spin } from "antd"

function getAvatarContent(imgUrl) {
    if (imgUrl) {
        return <img src={imgUrl} className={styles.avatarimg} />
    } else {
        return <div>
            <Icon type="plus" className={styles.icon}/>
            <div className="ant-upload-text">Upload</div>
        </div>
    }
}

function index({ value, onChange },ref) {
    const [loading, setLoading] = useState(false)
    return (
        <div>
            
            <Upload
                accept=".jpg,.png,.jpeg,.gif"
                ref={ref}
                listType="picture-card"
                showUploadList={false}
                action="/api/upload"
                name="imagefile"
                beforeUpload={() => {
                    setLoading(true)
                }}
                onChange={data => {
                    // console.log(onChange);
                    
                    if (data.file.response) {
                        onChange && onChange(data.file.response.path)
                        setLoading(false)
                    }

                }}
            >
                <Spin spinning={loading}>
                    <div className={styles.avatar}>
                        {getAvatarContent(value)}
                    </div>
                </Spin>
                
            </Upload>
        </div>
    )
}

export default React.forwardRef(index)